-- Leviathan (c) v.v.balashoff
-- based on Snowflakes effect for Löve
-- https://github.com/Cowa/love-snowflakes-effect
-- Copyright (c) 2016 Brice Thomas
-- The MIT License (MIT)
local Class = require('leviathan/Class')

local SnowSystem = Class:derive('UISnowSystem')

function SnowSystem:new(domain)
    self.name = 'SnowSystem'
    self.domain = domain
end

function SnowSystem:update(dt)
    local r = self.domain.components['Renderable']
    for _, c in pairs(r) do
        if c.id == 'SnowComponent' then
            if c.enabled then
                local t = love.timer.getTime()
                if c.time + c.upTime < t then
                    c.time = t
                    -- updating coordinates
                    c.angle = c.angle + 0.005
                    for i, p in pairs(c.particles) do
                        p.y = p.y + math.cos(c.angle + p.d) + 1 + p.r / 2
                        p.x = p.x + math.sin(c.angle) * 2
                        if p.y > c.h then
                            p.x = math.random() * c.w
                            p.y = -10
                        elseif p.x > c.w + 5 or p.x < -5 then
                            -- Exit from right
                            if (math.sin(c.angle) > 0) then p.x = -5
                                -- Exit from left
                            else p.x = c.w + 5
                            end
                        end
                        -- check previous values
                        local y = math.floor(p.y)
                        if not (p.yprev == y) then
                            c.entity.domain.changed = true
                        end
                        p.yprev = y
                    end
                end
            end
        end
    end
end

return SnowSystem
